package com.medical.service.impl;

import com.medical.constants.CacheConstants;
import com.medical.domain.LoginUserVO;
import com.medical.enums.ResultCode;
import com.medical.enums.TimeEnum;
import com.medical.exception.BusinessException;
import com.medical.mapper.UserMapper;
import com.medical.model.dto.LoginDto;
import com.medical.model.entity.User;
import com.medical.service.ILoginService;
import com.medical.service.RedisService;
import com.medical.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2024/6/25 22:47
 * @desc
 */
@Service
public class LoginServiceImpl implements ILoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Override
    public LoginUserVO login(LoginDto loginDto) {
        log.info("用户登录{}", loginDto);
        User user = userMapper.queryByUid(loginDto.getUsername());
        if (user == null){
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        if (!encoder.matches(loginDto.getPassword(), user.getPassword())){
            throw new BusinessException(ResultCode.USER_PASSWORD_ERROR);
        }
        LoginUserVO loginUserVO = LoginUserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .build();
        String token = jwtUtils.createToken(loginUserVO);
        redisService.setCacheObject(CacheConstants.USER_INFO_CACHE_KEY + user.getId(), token, TimeEnum.ONE_DAY);
        loginUserVO.setToken(token);
        return loginUserVO;
    }
}
